package com.bookstore.framework.config;

import com.bookstore.common.exception.BusinessException;
import com.bookstore.common.result.Result;
import com.bookstore.common.result.ResultCode;
import com.bookstore.common.validation.ValidationErrorCode;
import com.bookstore.common.validation.ValidationErrorResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Result<Void> handleBusinessException(BusinessException e) {
        log.error("业务异常: {}", e.getMessage());
        if (e.getErrorCode() != null) {
            return Result.error(Integer.parseInt(e.getErrorCode()), e.getMessage());
        }
        return Result.error(e.getMessage());
    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<Void> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e) {
        log.error("请求方式不支持: {}", e.getMessage());
        return Result.error("请求方式不支持: " + e.getMethod());
    }

    /**
     * 请求路径不存在
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public Result<Void> handleNoHandlerFoundException(NoHandlerFoundException e) {
        log.error("请求路径不存在: {}", e.getMessage());
        return Result.error(ResultCode.NOT_FOUND);
    }

    /**
     * 权限校验异常
     */
    @ExceptionHandler(AccessDeniedException.class)
    public Result<Void> handleAccessDeniedException(AccessDeniedException e) {
        log.error("权限校验异常: {}", e.getMessage());
        return Result.forbidden();
    }

    /**
     * 认证失败
     */
    @ExceptionHandler(BadCredentialsException.class)
    public Result<Void> handleBadCredentialsException(BadCredentialsException e) {
        log.error("认证失败: {}", e.getMessage());
        return Result.unauthorized();
    }

    /**
     * 参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<List<ValidationErrorResponse>> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("参数校验异常: {}", e.getMessage());
        List<ValidationErrorResponse> errors = collectValidationErrors(e.getBindingResult());
        return Result.validateFailed("参数校验失败", errors);
    }

    /**
     * 参数绑定异常
     */
    @ExceptionHandler(BindException.class)
    public Result<List<ValidationErrorResponse>> handleBindException(BindException e) {
        log.error("参数绑定异常: {}", e.getMessage());
        List<ValidationErrorResponse> errors = collectValidationErrors(e.getBindingResult());
        return Result.validateFailed("参数绑定失败", errors);
    }

    /**
     * 参数校验异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result<List<ValidationErrorResponse>> handleConstraintViolationException(ConstraintViolationException e) {
        log.error("参数校验异常: {}", e.getMessage());
        List<ValidationErrorResponse> errors = collectConstraintViolations(e.getConstraintViolations());
        return Result.validateFailed("参数校验失败", errors);
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public Result<Void> handleException(Exception e) {
        log.error("系统异常: ", e);
        return Result.error("系统异常，请联系管理员");
    }
    
    /**
     * 收集校验错误信息
     * @param bindingResult 绑定结果
     * @return 校验错误响应列表
     */
    private List<ValidationErrorResponse> collectValidationErrors(BindingResult bindingResult) {
        List<ValidationErrorResponse> errors = new ArrayList<>();
        
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            ValidationErrorResponse error = new ValidationErrorResponse();
            error.setField(fieldError.getField());
            error.setRejectedValue(fieldError.getRejectedValue());
            error.setMessage(fieldError.getDefaultMessage());
            
            // 获取错误码
            String errorCode = fieldError.getCode();
            ValidationErrorCode validationErrorCode = ValidationErrorCode.getByConstraintType(errorCode);
            if (validationErrorCode != null) {
                error.setCode(validationErrorCode.getCode());
            } else {
                error.setCode("V000");
            }
            
            errors.add(error);
            
            // 记录详细日志
            log.debug("字段校验错误: field={}, value={}, message={}, code={}",
                    error.getField(), error.getRejectedValue(), error.getMessage(), error.getCode());
        }
        
        return errors;
    }
    
    /**
     * 收集约束违反信息
     * @param violations 约束违反集合
     * @return 校验错误响应列表
     */
    private List<ValidationErrorResponse> collectConstraintViolations(Set<ConstraintViolation<?>> violations) {
        List<ValidationErrorResponse> errors = new ArrayList<>();
        
        for (ConstraintViolation<?> violation : violations) {
            ValidationErrorResponse error = new ValidationErrorResponse();
            
            // 获取字段路径
            String propertyPath = violation.getPropertyPath().toString();
            // 如果路径包含方法名，则去除方法名部分
            if (propertyPath.contains(".")) {
                propertyPath = propertyPath.substring(propertyPath.lastIndexOf(".") + 1);
            }
            error.setField(propertyPath);
            
            error.setRejectedValue(violation.getInvalidValue());
            error.setMessage(violation.getMessage());
            
            // 获取错误码
            String constraintType = violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName();
            ValidationErrorCode validationErrorCode = ValidationErrorCode.getByConstraintType(constraintType);
            if (validationErrorCode != null) {
                error.setCode(validationErrorCode.getCode());
            } else {
                error.setCode("V000");
            }
            
            errors.add(error);
            
            // 记录详细日志
            log.debug("约束违反错误: field={}, value={}, message={}, code={}",
                    error.getField(), error.getRejectedValue(), error.getMessage(), error.getCode());
        }
        
        return errors;
    }
    
    /**
     * 获取当前请求
     */
    private HttpServletRequest getCurrentRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes != null ? attributes.getRequest() : null;
    }
}